import { MessageBox } from 'element-ui';
import apis from '@assets/js/apis';
import xlsx from 'xlsx';

class common {
	/**
	 * 判断是否为空
	 * @param {All} value - 需要判断的数据
	 * @returns {Boolean}
	 */
	isEmpty(value) {
		switch (typeof value) {
			case 'undefined':
				return true;
			case 'string':
				if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length === 0 || value == 'null') return true;
				break;
			case 'boolean':
				if (!value) return true;
				break;
			case 'number':
				// if (0 === value || isNaN(value)) return true;
				if (isNaN(value)) return true;
				break;
			case 'object':
				if (null === value || value.length === 0) return true;
				// Date对象
				if (value instanceof Date) return false;
				for (var i in value) {
					return false;
				}
				return true;
		}
		return false;
	}

	/**
	 *
	 * @param {Number} n1 开始值
	 * @param {Number} n2 结束值
	 * @param {Sting} title 标题名称
	 */
	validateNumber(n1, n2, title) {
		return new Promise((resolve) => {
			if (this.isEmpty(n1) && this.isEmpty(n2)) return resolve();

			if (
				(this.isEmpty(n1) && !this.isEmpty(n2)) ||
				(!this.isEmpty(n1) && this.isEmpty(n2)) ||
				!/^[0-9]\d*$/.test(n1) ||
				!/^[0-9]\d*$/.test(n2) ||
				Number(n1) >= Number(n2)
			) {
				return this.alert('请输入正确的' + title + '整数区间');
			}
			console.log(n1 >= n2, n1, n2);

			resolve();
		});
	}

	/**
	 * 搜索对象转换成数组列表
	 * @param {Object} obj - 转换对象
	 */
	searchFrame(obj) {
		const arr = [];
		for (const key in obj) {
			if (obj.hasOwnProperty(key)) {
				arr.push({ id: key, value: obj[key] });
			}
		}
		return arr;
	}

	/**
	 * 搜索对象转换成带全部的数组列表
	 * @param {Object} obj - 转换对象
	 * @param {Boolean} type - 是否需要全部
	 */
	searchFrameAll(obj, type) {
		const arr = type ? [] : [{ id: '', value: '全部' }];
		for (const key in obj) {
			if (obj.hasOwnProperty(key)) {
				arr.push({ id: key, value: obj[key] });
			}
		}
		return arr;
	}

	/**
	 * 搜索数组转换成带全部的数组列表
	 * @param {Array} arr - 转换原数组
	 * @param {Number} level - 当前层级
	 */
	searchFrameArea(arr, level = 0) {
		let newArr = [
			{
				label: '全部',
				value: '全部',
				leaf: true,
			},
		];
		arr.forEach((res) =>
			newArr.push({
				label: res,
				value: res,
				leaf: level >= 1,
				children: [],
			})
		);
		return newArr;
	}

	sessionStorageGet(key) {
		const value = sessionStorage.getItem(key);
		return value && JSON.parse(value);
	}

	sessionStorageSet(key, value) {
		sessionStorage.setItem(key, JSON.stringify(value));
	}

	/**
	 * 时间过滤
	 * @param {date：Data} 需要过滤的时间
	 * @param {format:String} 过滤格式
	 * @returns {*}
	 */
	dateFormat(date, fmt = 'YYYY-MM-DD HH:mm:ss') {
		if (!date) {
			return '';
		}
		if (typeof date === 'string') {
			date = new Date(date.replace(/-/g, '/'));
		}
		if (typeof date === 'number') {
			date = new Date(date);
		}
		var o = {
			'M+': date.getMonth() + 1,
			'D+': date.getDate(),
			'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
			'H+': date.getHours(),
			'm+': date.getMinutes(),
			's+': date.getSeconds(),
			'q+': Math.floor((date.getMonth() + 3) / 3),
			S: date.getMilliseconds(),
		};
		var week = {
			'0': '\u65e5',
			'1': '\u4e00',
			'2': '\u4e8c',
			'3': '\u4e09',
			'4': '\u56db',
			'5': '\u4e94',
			'6': '\u516d',
		};
		if (/(Y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
		}
		if (/(E+)/.test(fmt)) {
			fmt = fmt.replace(
				RegExp.$1,
				(RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') +
					week[date.getDay() + '']
			);
		}
		for (var k in o) {
			if (new RegExp('(' + k + ')').test(fmt)) {
				fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
			}
		}
		return fmt;
	}

	/** 输入框验证文字验证 */
	checkInput = (rule, value, callback) => {
		this.isEmpty(value) ? callback(new Error()) : callback();
	};

	/**输入框数字验证 */
	checkNum = (rule, value, callback) => {
		/^[1-9]\d*$/.test(value) ? callback() : callback(new Error());
	};

	/**输入框数字验证且最多有两位小数 */
	checkNumFlotTwo = (rule, value, callback) => {
		/^[0-9]+(.?[0-9]{1,2})?$/.test(value) ? callback() : callback(new Error());
	};

	/** 数字且小于100 */
	numMax = (rule, value, callback) => {
		/^([0-9]{1,2}|100)$/.test(value) ? callback() : callback(new Error());
	};

	/**输入框不能为空 */
	canleIsEmpty = (rule, value, callback) => {
		/\S/.test(value) ? callback() : callback(new Error());
	};

	/**版本号 */
	versionTest = (rule, value, callback) => {
		/^\d+\.\d+\.\d+$/.test(value) ? callback() : callback(new Error());
	};

	checkFloor = (rule, value, callback) => {
		/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(value) ? callback() : callback(new Error());
	};

	/**输入框用户账号验证 */
	checkUserName = (rule, value, callback) => {
		if (/^[a-zA-Z][a-zA-Z0-9_-]{3,15}$/.test(value)) {
			callback();
		} else {
			callback(new Error());
		}
	};

	/**输入框用户密码验证 */
	checkUserPwd = (rule, value, callback) => {
		if (/^.{6,20}$/.test(value)) {
			callback();
		} else {
			callback(new Error());
		}
	};

	checkNothing = (rule, value, callback) => {
		callback();
	};

	//转化为分单位
	fomatMin(obj) {
		if (obj.constructor === Object) {
			let newObj = {};
			Object.keys(obj).forEach((ele) => {
				newObj[ele] = obj[ele] * 100;
			});
			return newObj;
		}
	}

	//转化为元
	fomaty(obj) {
		if (obj.constructor === Object) {
			let newObj = {};
			Object.keys(obj).forEach((ele) => {
				newObj[ele] = obj[ele] / 100;
			});
			return newObj;
		}
	}

	// 提示
	alert(msg) {
		MessageBox.alert(msg, '提示', {
			confirmButtonText: '确定',
		});
	}

	/**
	 *
	 * @param {String} api 接口地址
	 * @param {Object} params 参数对象
	 */
	excelExport(api, params) {
		let url =
			location.hostname == 'localhost' || location.port == '8080'
				? `${location.origin}/admin/admin/${apis[api]}`
				: `${location.origin}/admin/${apis[api]}`;

		url = params ? url + '?' + params : url;
		window.open(url);
	}

	/**
	 * 深拷贝方法
	 * @param {Object} data 拷贝对象
	 */
	deepCopy(data) {
		let result = Array.isArray(data) ? [] : {};
		for (const key in data) {
			if (typeof data[key] === 'object' && data[key] !== null) {
				result[key] = this.deepCopy(data[key]); //递归复制
			} else {
				result[key] = data[key];
			}
		}
		return result;
	}

	// sheet转换blob
	sheet2blob(sheet, sheetName) {
		sheet = xlsx.utils.aoa_to_sheet(sheet);
		sheetName = sheetName || 'sheet1';
		var workbook = {
			SheetNames: [sheetName],
			Sheets: {},
		};
		workbook.Sheets[sheetName] = sheet;
		// 生成excel的配置项
		var wopts = {
			bookType: 'xlsx', // 要生成的文件类型
			bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
			type: 'binary',
		};
		var wbout = xlsx.write(workbook, wopts);
		var blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
		// 字符串转ArrayBuffer
		function s2ab(s) {
			var buf = new ArrayBuffer(s.length);
			var view = new Uint8Array(buf);
			for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
			return buf;
		}
		return blob;
	}

	// 下载转换的excel
	openDownloadDialog(url, saveName) {
		if (typeof url == 'object' && url instanceof Blob) {
			url = URL.createObjectURL(url); // 创建blob地址
		}
		var aLink = document.createElement('a');
		aLink.href = url;
		aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
		var event;
		if (window.MouseEvent) event = new MouseEvent('click');
		else {
			event = document.createEvent('MouseEvents');
			event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		}
		aLink.dispatchEvent(event);
	}

	getTimerString(q) {
		let t = new Date(q * 1000),
			y = t.getFullYear(),
			m = t.getMonth() + 1 < 10 ? '0' + (t.getMonth() + 1) : t.getMonth(),
			d = t.getDate() < 10 ? '0' + t.getDate() : t.getDate(),
			h = t.getHours() < 10 ? '0' + t.getHours() : t.getHours(),
			mm = t.getMinutes() < 10 ? '0' + t.getMinutes() : t.getMinutes(),
			s = t.getSeconds() < 10 ? '0' + t.getSeconds() : t.getSeconds();

		return `${y}-${m}-${d} ${h}:${mm}:${s}`;
	}

	/**
	 *
	 * @param {String} val 值
	 * @param {String} key 查找的键
	 * @param {Array} list 查找的数组源
	 * @returns
	 */
	findKey(val, key, list) {
		let data = {};
		if (val === '' || val === null) return false;
		return list.find((item) => {
			if (item[key] === val) {
				return (data = item);
			}
		});
	}

	/**
	 *
	 * @param {String} api 接口地址
	 * @param {Object} params 导出参数对象
	 */
	exportData(api, params) {
		let url =
			process.env.NODE_ENV === 'development'
				? `http://openapi.t.17usoft.net/outsourceapi/admin${api}`
				: `${location.origin}/outsourceapi/admin${api}`;
		let index = 0;
		if (params) {
			for (const key in params) {
				url += `${index ? '&' : '?'}${key}=${params[key]}`;
				index++;
			}
		}
		window.open(url);
	}
}

export default new common();
